package com.lyn.serialPort;

import android.text.TextUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * created by lyn at 2021/11/6
 */
public class ConversionUtil {

    public static byte[] stringToByteArray(String str) {
        return str.getBytes(StandardCharsets.UTF_8);
    }

    public static byte[] stringToByteArray(String str, Charset charset) {
        return str.getBytes(charset);
    }

    public static String ByteArrayToString(byte[] data) {
        return new String(data).toString();
    }

    public static String ByteArrayToString(byte[] data, Charset charset) {
        return new String(data, charset).toString();
    }

    // 判断奇数或偶数，位运算，最后一位是1则为奇数，为0是偶数
    public static int isOdd(int num) {
        return num & 1;
    }

    /**
     * Hex字符串转byte
     *
     * @param inHex
     * @return
     */
    public static byte HexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    /**
     * 1字节转2个Hex字符
     *
     * @param inByte
     * @return
     */
    public static String Byte2Hex(Byte inByte) {
        return String.format("%02x", new Object[]{inByte}).toUpperCase();
    }

    /**
     * 字节数组转转hex字符串
     * @param inBytArr
     * @return
     */
    public static String ByteArrToHex(byte[] inBytArr) {
        StringBuilder strBuilder = new StringBuilder();
        for (byte valueOf : inBytArr) {
            strBuilder.append(Byte2Hex(Byte.valueOf(valueOf)));
        }
        return strBuilder.toString();
    }

    /**
     * 字节数组转转hex字符串，可选长度
     * @param inBytArr
     * @param offset
     * @param byteCount
     * @return
     */
    public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount) {
        StringBuilder strBuilder = new StringBuilder();
        int j = byteCount;
        for (int i = offset; i < j; i++) {
            strBuilder.append(Byte2Hex(Byte.valueOf(inBytArr[i])));
        }
        return strBuilder.toString();
    }


    /**
     * 把hex字符串转字节数组
     * @param inHex
     * @return
     */
    public static byte[] HexToByteArr(String inHex) {
        if (TextUtils.isEmpty(inHex)) {
            return null;
        }
        byte[] result;
        int hexLen = inHex.length();
        if (isOdd(hexLen) == 1) {
            hexLen++;
            result = new byte[(hexLen / 2)];
            inHex = "0" + inHex;
        } else {
            result = new byte[(hexLen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexLen; i += 2) {
            result[j] = HexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

}
